package lookas.xml;

import java.io.File;
import java.io.InputStream;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.w3c.dom.Document;

public class XML {
	public static void save(Document xmldoc, String type, String dest)
			throws TransformerException {

		Transformer transformer = prepareTransform(type);
		transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		StreamResult result = new StreamResult(new File(dest));
		transformer.transform(new DOMSource(xmldoc), result);
	}

	private static Transformer prepareTransform(String type)
			throws TransformerException {

		InputStream resource = null;
		if (type != null) {
			String xslt = String.format("/xslt/%s.xsl", type);
			resource = XML.class.getResourceAsStream(xslt);
		}
		if (resource == null)
			return TransformerFactory.newInstance().newTransformer();
		StreamSource source = new StreamSource(resource);
		return TransformerFactory.newInstance().newTransformer(source);
	}
}
